//
//  APPLEEmoticonToolBar.swift
//  123
//
//  Created by pangjiaxing on 16/1/13.
//  Copyright © 2016年 pangjiaxing. All rights reserved.
//

import UIKit

enum  APPLEEmoticonType:Int{
    
    case Recent = 1000
    case Default = 1001
    case Emoji = 1002
    case Lxh = 1003
    
}

protocol APPLEEmoticonToolBarDelegate:NSObjectProtocol{
    func emoticonButtonSelectedWithType(type:APPLEEmoticonType)
}

class APPLEEmoticonToolBar: UIStackView {
    
    weak var delegate:APPLEEmoticonToolBarDelegate?
    
    private var currentSelectedButton:UIButton?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI(){
        
        distribution = .FillEqually
        
        addChildButton("最近", bgImageNamed: "compose_emotion_table_left", type: .Recent)
        addChildButton("默认", bgImageNamed: "compose_emotion_table_mid", type: .Default)
        addChildButton("Emoji", bgImageNamed: "compose_emotion_table_mid", type: .Emoji)
        addChildButton("浪小花", bgImageNamed: "compose_emotion_table_right", type: .Lxh)
        selectedButtonWithSection(1)
    }
    
    private func addChildButton(title: String,bgImageNamed: String, type: APPLEEmoticonType){
        let button = UIButton()
        // 监听按钮的点击
        button.addTarget(self, action: "didChildButton:", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 设置 tag 以区哪一个按钮点击
        button.tag = type.rawValue
        
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        // 设置文字以及不同状态下的文字颜色
        button.setTitle(title, forState: UIControlState.Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Selected)
        
        // 设置不同状态的背景图
        button.setBackgroundImage(UIImage(named: "\(bgImageNamed)_normal"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "\(bgImageNamed)_selected"), forState: UIControlState.Selected)
        
        addArrangedSubview(button)
    }
    
    @objc private func didChildButton(button:UIButton){
        
        if currentSelectedButton == button {
            return
        }
        
        currentSelectedButton?.selected = false
        button.selected = true
        currentSelectedButton = button
        
        delegate?.emoticonButtonSelectedWithType(APPLEEmoticonType(rawValue: button.tag)!)
    }
    
    func selectedButtonWithSection(section:Int){
        let button = viewWithTag(section+1000) as! UIButton
        if button == currentSelectedButton {
            return
        }
        currentSelectedButton?.selected = false
        button.selected = true
        currentSelectedButton = button
        
    }
}
